<?php


namespace app\partner\controller;


use think\Db;
use think\Validate;

class Partner extends Common
{

    /**
     * 合伙人列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function partnerList()
    {
        $id = $this->id;
        $db = Db::name('partner')->join('user_manage', 'partner.uid = user_manage.id')->where('partner.super_partner_id', $id);
        if (input('nickname') != '') {
            $db = $db->where('user_manage.nickname', input('nickname'));
        }
        if (input('code') != '') {
            $db = $db->where('user_manage.code', input('code'));
        }
        if (input('tel') != '') {
            $db = $db->where('user_manage.tel', input('tel'));
        }
        if (input('status') != '') {
            $db = $db->where('partner.status', input('status'));
        }
        if (input('startTime') != '' && input('endTime') != '') {
            $db = $db->where('partner.reg_time', '>=', strtotime(input('startTime')))->whereTime('partner.reg_time', '<', strtotime(input('endTime')));
        }
        $data['data'] = $db->field('headimgurl,partner.id as id,nickname,code,tel,partner.status as status,partner.reg_time,rebate_percent,partner.money as money,partner.remark')->page(input('page', 1), input('limit', 20))->order(input('order', 'partner.reg_time'), input('sort', 'desc'))->select();

        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['nickname'] = emoji_decode($data['data'][$k]['nickname']);
            $data['data'][$k]['tuanduirenshu'] = Db::name('user_manage')->where('partner_id', $v['id'])->count();
            $userOrderInfo = $this->getSonPartnerOrderInfo($v['id']);
            $data['data'][$k]['youxiaodingdan'] = $userOrderInfo['count'];
            $data['data'][$k]['leijixiaoshou'] = $userOrderInfo['user_buy_price'];
            $data['data'][$k]['leijilirun'] = Db::name('partner_liushui')->where('partner_id', $v['id'])->where('money', '>', 0)->sum('money');
        }


        $data['total_num'] = $db->count();
        returnSuccess($data);
    }


    private function getSonPartnerOrderInfo($id)
    {
        $data['count'] = 0;
        $data['user_buy_price'] = 0;
        $uids = Db::name('user_manage')->where('partner_id', $id)->column('id');
        if(empty($uids)) return $data;
        $tbOrder = Db::name('tb_order')->where('uid', 'in', $uids)->where('order_type', 1)->where('is_weiquan', 0)->where('order_status', '<>', 0)->field('SUM(user_buy_price) as user_buy_price,count(1) as count')->find();
        $jdOrder = Db::name('jd_order')->where('uid', 'in', $uids)->where('order_status', '<>', 0)->field('SUM(user_buy_price) as user_buy_price,count(1) as count')->find();
        $pddOrder = Db::name('pdd_order')->where('uid', 'in', $uids)->where('order_status', '<>', 0)->field('SUM(user_buy_price) as user_buy_price,count(1) as count')->find();
        $data['count'] = $tbOrder['count'] + $jdOrder['count'] + $pddOrder['count'];
        $data['user_buy_price'] = (string)($tbOrder['user_buy_price'] + $jdOrder['user_buy_price'] + $pddOrder['user_buy_price']);
        dump($uids);
        return $data;
    }


    /**
     * 通过手机号查询用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserInfoByTel()
    {
        $tel = input('tel');
        if (!$tel) returnError('请输入手机号');
        $userInfo = Db::name('user_manage')->where('tel', $tel)->field('id as uid,nickname,code')->find();

        if ($userInfo) {
            $rebate = $this->getPartnerRebatePercent(true);
            $userInfo = array_merge($rebate,$userInfo);
            returnSuccess($userInfo);
        } else {
            returnError('用户不存在！');
        }
    }
   /*
    * 获取上级推荐人奖励比例
    * */
    public function getPartnerInfoRebate()
    {
        $id = $this->id;
        $superInfo = Db::name('user_manage')
            ->alias('o')
            ->join('super_partner u', 'u.uid=o.id', 'LEFT')
            ->where('u.id', $id)
            ->field('u.id,o.nickname,o.code,u.user_one_rebate_percent')
            ->find();
        if (!empty($superInfo)){
            $info = $this->getPartnerInfoMaxPercent($id);
            $edit_log = $this->getSonpartnerLog($id);
            $superInfo['edit_num'] = $edit_log['edit_count'];
            $superInfo['max_percent'] = $info['max_percent'];
            $superInfo['now_percent'] = $info['now_percent'];
            $superInfo['max_partner_percent'] = $info['max_partner_percent'] ? $info['max_partner_percent'] : 0;
            $superInfo['max_edit_num'] = 12;
            $superInfo['min_percent'] = 5;
            returnSuccess($superInfo);
        } else {
            returnError('用户不存在');
        }
    }
    /*
     *修改上级推荐人奖励比例
     * */
    public  function partnerMaxPercentEdit()
    {
        $id = $this->id;
        $min_percent = 5;
        $requestData = input();
        $info = $this->getPartnerInfoMaxPercent($id);
        $max_percent = $info['max_percent'];
        $max_partner_percent = Db::name('partner')->where('super_partner_id',$id)->field('max(rebate_percent) as max_partner_percent')->find();
        $validate = Validate::make([
            'rebate_percent|提成比例' => 'require|number',
        ]);
        if (!$validate->check($requestData)) {
            returnError($validate->getError());
        }
        if ($requestData['rebate_percent'] > $max_percent || $requestData['rebate_percent'] < 0){
            returnError('最大可设置比例为！' . $max_percent);
        }
        if ($requestData['rebate_percent'] < $min_percent){
            returnError('最小可设置比例为！' . $min_percent);
        }
        if ($requestData['rebate_percent'] > 28 - $max_partner_percent['max_partner_percent']){
            returnError('设置比例超过可设定值！');
        }
        Db::name('super_partner')->where('id', $id)->update([
            'user_one_rebate_percent' => $requestData['rebate_percent'],
            'remark' => !empty($requestData['remark']) ? $requestData['remark'] : '',
        ]);
        $edit_num = $this->getSonpartnerLog($id);;
        if ($edit_num['log_count'] < 12 || $edit_num['log_count'] >= 0){
            Db::name('super_partner_operate_log')->insert([
                'super_partner_id' => $this->id,
                'value' => $requestData['rebate_percent'],
                'type' => 1,
                'time' => time(),
            ]);
        }
        returnSuccess([], '编辑成功！');
    }
    /*
     * 获取上级推荐人可修改最大奖励比例
     * */
    public function getPartnerInfoMaxPercent($id)
    {
        $max_percent = Db::name('partner')->where('super_partner_id',$id)->field('max(rebate_percent) as max_percent')->find();
        $super_percent = Db::name('super_partner')->where('id',$id)->field('user_one_rebate_percent')->find();
        $data['now_percent'] = $super_percent['user_one_rebate_percent'];
        $data['max_partner_percent'] = $max_percent['max_percent'];
        $data['max_percent'] = 28 - $max_percent['max_percent'];
        return $data;
    }
    /*
     * 获取上级推荐人可修改最大奖励次数
     * */
    public function getSonpartnerLog($id)
    {
        $xia_y_time = mktime(0,0,0,1,1,date('Y')+1);
        $log_count = Db::name('super_partner_operate_log')
            ->where('super_partner_id',$id)
            ->where('time', '<', $xia_y_time)
            ->count();
        $data['log_count'] = $log_count;
        $data['edit_count'] = 12 - $log_count;
        return $data;
    }
    public function partnerAdd()
    {
        $requestData = input();
        $validate = Validate::make([
            'uid|用户id' => 'require|number',
            'rebate_percent|提成比例' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            returnError($validate->getError());
        }
        $user = Db::name('user_manage')->find($requestData['uid']);
        if (!$user) returnError('用户不存在！');

        $sonpartner = Db::name('partner')->where('uid', $requestData['uid'])->find();
        if ($sonpartner) returnError('该用户已经是合伙人，不能重复添加！');

        $sonpartner = Db::name('super_partner')->where('uid', $requestData['uid'])->find();
        if ($sonpartner) returnError('该用户已经是超级合伙人，不能添加！');


        $partner = Db::name('super_partner')->find($this->id);
        $data['userRebate'] = $partner['user_one_rebate_percent'];
        if ($requestData['rebate_percent'] > 28 - $partner['user_one_rebate_percent'] || $requestData['rebate_percent'] < 0) {
            returnError('最大可设置比例为！' . (28 - $partner['user_one_rebate_percent']));
        }

        Db::name('partner')->insert([
            'uid' => $requestData['uid'],
            'rebate_percent' => $requestData['rebate_percent'],
            'reg_time' => time(),
            'super_partner_id' => $this->id,
        ]);
        returnSuccess([], '添加成功！');
    }


    /**
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPartnerRebatePercent($bool = false)
    {
        $id = $this->id;
        $partner = Db::name('super_partner')->find($id);
        $data['userRebate'] = $partner['user_one_rebate_percent'];
        $data['partnerRebate'] = 28 - $partner['user_one_rebate_percent'];
        if($bool)
        {
            return $data;
        }

        returnSuccess($data);
    }


    public function partnerEdit()
    {
        $id = $this->id;
        $pid = input('id');//合伙人id
        $requestData = input();
        $partner = Db::name('super_partner')->find($this->id);
        if ($requestData['rebate_percent'] > 28 - $partner['user_one_rebate_percent'] || $requestData['rebate_percent'] < 0) {
            returnError('最大可设置比例为！' . (28 - $partner['user_one_rebate_percent']));
        }
        Db::name('partner')->where('id', $pid)->update([
            'rebate_percent' => $requestData['rebate_percent'],
            'remark' => !empty($requestData['remark']) ? $requestData['remark'] : '',
        ]);
        returnSuccess([], '编辑成功！');
    }


    public function partnerStatus()
    {
        $requestData = input();
        $validate = Validate::make([
            'status|状态' => 'require|in:0,1',
            'id' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            returnError($validate->getError());
        }

        $partner = Db::name('partner')->find($requestData['id']);

        if ($partner['status'] == $requestData['status']) {

            if ($partner['status'] == 1) {
                returnError('该合伙人已经是启用状态!');
            } else {
                returnError('该合伙人已经是禁用状态！');
            }
        }


        Db::name('partner')->where('id', $requestData['id'])->update([
            'status' => $requestData['status'],
            'remark' => $requestData['remark'],
        ]);
        Db::name('partner_status_log')->insert([
            'super_partner_id' => $this->id,
            'partner_id' => $requestData['id'],
            'status' => $requestData['status'],
            'remark' => $requestData['remark'],
            'time' => time()
        ]);
        returnSuccess([], '修改成功！');
    }


    public function partnerStatusLog()
    {
        $id = $this->id;
        $db = Db::name('partner_status_log')
            ->join('partner', 'partner.id = partner_status_log.partner_id')
            ->join('user_manage', 'partner.uid = user_manage.id')
            ->where('partner_status_log.super_partner_id', $id);


        if (input('nickname') != '') {
            $db = $db->where('user_manage.nickname', input('nickname'));
        }

        if (input('code') != '') {
            $db = $db->where('user_manage.code', input('code'));
        }
        if (input('tel') != '') {
            $db = $db->where('user_manage.tel', input('tel'));
        }
        if (input('startTime') != '' && input('endTime') != '') {
            $db = $db->where('partner_status_log.time', '>=', strtotime(input('startTime')))->whereTime('partner_status_log.time', '<', strtotime(input('endTime')));
        }
        $data['data'] = $db->field('user_manage.headimgurl,user_manage.nickname,user_manage.tel,user_manage.code,partner_status_log.status,partner_status_log.time,partner_status_log.remark')->page(input('page',1),input('limit',20))->order('partner_status_log.id','desc')->select();

        foreach ($data['data'] as  $k => $v){
            $data['data'][$k]['nickname'] = emoji_decode($data['data'][$k]['nickname']);
            $data['data'][$k]['time'] = date('Y-m-d H:i:s',$data['data'][$k]['time']);
        }

        $data['total_num'] = $db->count();
        returnSuccess($data);
        returnSuccess($data);
    }


}